﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace baomi.Models
{
    /// <summary>
    /// 加密类
    /// </summary>
    internal class MyEncoder
    {
        /// <summary>
        /// 明文
        /// </summary>
        public string Plaintext { get; set; }

        /// <summary>
        /// 密文
        /// </summary>
        public string Cipher { get; set; }

        /// <summary>
        /// 密钥
        /// </summary>
        public string Key { get; set; }
        ///<summary>
        /// 加密动作
        /// </summary>
        public void Encode ()
        {
            //计算密钥长度
            int length = Key.Length;
            //将字符串转换为数组
            char[] plaintext = Plaintext.ToCharArray();
            char[] key = Key.ToCharArray();
            char[] cipher = new char[Plaintext.Length];
            //开始加密
            for (int i = 0; i < Plaintext.Length; i++)
            {
                //计算每一个密文所对应的数字
                int _cipher = (MyFunction(plaintext[i] )+ MyFunction(key[i % length]))%26;
                //将数字转换为大写字母
                char ch = Convert.ToChar(_cipher + 65);
                cipher[i] = ch;
            }
            //将得到的密文数组转为字符串
            Cipher = new string(cipher);

        }

        /// <summary>
        /// 返回指定字符在字母表中的序号
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
          private int MyFunction(char ch)
        {
            if (ch >= 'a' && ch <= 'z')
                return ch - 'a';
            if (ch >= 'A' && ch <= 'Z')
                return ch - 'A';
            else return 0;

        }

    }
}
